package com.archway.appframe.orm;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.archway.appframe.db.AppframeDatasourceConfig;
import com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor;


@Configuration
@PropertySource({ "classpath:config/database/persistence.properties"}) 
@MapperScan(basePackages="com.archway.**.dao.interfaces")
@Import(value={AppframeDatasourceConfig.class})
public class AppframePersistenceConfig {
	
	/**
	 * 配合@PropertySource 标注的文件使用
	 */
	@Autowired
	private Environment env;
	
    @Autowired
    DataSource dataSource;

	/**********************************************mybatis******************************************************/	
    
    /**
     * 
     * <strong>(please edit it when context changed)</strong></br>
     * <h1>描述:</h1>
     * <li>描述细节列表</li> 
     * <li>描述细节列表</li>  
     * @return
     * @throws Exception
     * @author lirn
     * @createDate 2014年3月11日 下午11:20:01
     */
    @Bean
	public SqlSessionFactory createMybatisSessionFactory() throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(this.dataSource);
		
		Interceptor[] plugins = new Interceptor[1];
		plugins[0] = new OffsetLimitInterceptor();
		Properties prop = new  Properties();//分页插件
		prop.setProperty("dialectClass", "com.github.miemiedev.mybatis.paginator.dialect.MySQLDialect");
		plugins[0].setProperties(prop);
		sessionFactory.setPlugins(plugins);
//		
		//sessionFactory.setConfigurationProperties(this.mybatisProperties());
		return sessionFactory.getObject();
	}
	
	
    final Properties mybatisProperties() {
        return new Properties() {
            { 	
                //this.put("hibernate.dialect", env.getProperty("jdbc.driverClassName"));
                //this.put("hibernate.hbm2ddl.auto", env.getProperty("jdbc.url"));
                //this.put("hibernate.show_sql", env.getProperty("jdbc.user"));
            }
        };
    }
	
}
